

from django.shortcuts import render
from django.utils.crypto import random

from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from django.http import HttpResponse

from meiduo_mall.apps.verifications import serializers
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code

from . import constants
# Create your views here.

import logging
#日志记录器
logger = logging.getLogger('django')

class SMSCodeView(GenericAPIView):
    #'''短信验证码'''
    # 接受参数：mobile,image_code_id,text
    # 校验参数：比较用户传入的图片验证码和服务器存储的是否一致

    #序列化器
    serializer_class = serializers.InageCodeCheckSerializers

    def get(self,request,mobile):

        #创建序列化器
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

       # 生成随机的短信验证码:6位验证码，不够6位需要补0
        sms_code = '%06d' %random.randint(0,999999)
        logger.info(sms_code)
        print(sms_code)

       #发送短息验证码#
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_IMAGE_CODE_REDIS_EXPIRES // 60],1)

        #异步发送短信
        #delay:将异步任务添加到redis 表示用户出发了异步任务 worker就知道此时需要取redis中读取任务
        send_sms_code.delay(mobile,sms_code)

       #存储短信验证码
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex('sms_%s' %mobile,constants.SMS_IMAGE_CODE_REDIS_EXPIRES,sms_code)

        #使用redis管道概念 实行异步执行提高redis执行效率
        pl = redis_conn.pipeline()

        #存储短信验证码
        pl.setex('sms_%s' % mobile, constants.SMS_IMAGE_CODE_REDIS_EXPIRES, sms_code)

        #给每个数值绑定时间60s防止客户频繁发送恶意短信
        pl.setex('send_flag_%s' %mobile,constants.SEND_CODE_FLAG_INTERIVE,1)

        # 调用execute
        pl.execute()

        return Response({'message':'OK'})


class ImageCodeView(APIView):
    '''图片验证码'''

    def get(self,request,image_code_id):
        '''提供图片那验证码'''
        #生成图片验证码
        text,image = captcha.generate_captcha()
        logger.info(text)
        print(text)

        #将图片验证码内容保存到redis
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.set('img_%s'%image_code_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)

        #将图片验证码响应给客户(image/jpg)
        return HttpResponse(image,content_type='image/jpg')






































